<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      title="合同列表"
      rowKey="id"
      :columns="columns"
      :requestApi="ContractApi.page"
      :dataCallback="dataCallback"
      :initParam="initParam"
      :searchCol="{ xs: 2, sm: 3, md: 4, lg: 6, xl: 8 }"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" v-hasPermi="['sys:contract:add']" @click="openDrawer('新增')">新增商品</el-button>
        <el-button type="success" :icon="Printer" v-hasPermi="['sys:contract:print']" @click="batchPrint">批量打印</el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="EditPen" v-hasPermi="['sys:contract:edit']" @click="openDrawer('编辑', scope.row)">编辑</el-button>
        <el-button type="success" link :icon="Printer" v-hasPermi="['sys:contract:print']" @click="printContract(scope.row)">打印</el-button>
        <el-button type="info" link :icon="Share" v-hasPermi="['sys:contract:audit']" v-if="scope.row.status === 0" @click="startApproval(scope.row)">审核</el-button>
      </template>
    </ProTable>
    <ContractDialog ref="dialogRef" />
    <ProductDialog ref="productDialogRef" />

    <!-- 打印内容 - 优化版 -->
    <div id="printContent" style="position: fixed; top: -10000px; left: -10000px; display: none">
      <div v-for="contract in printContracts" :key="contract.id" class="print-page">
        <!-- 页面头部 -->
        <div class="print-header">
          <div class="company-info">
            <h1>XX公司销售合同</h1>
            <p>地址：XX市XX区XX路XX号 | 电话：010-XXXXXXXX | 邮箱：contact@example.com</p>
          </div>
          <div class="contract-info">
            <p>合同编号: {{ contract.number }}</p>
            <p>打印时间: {{ new Date().toLocaleString() }}</p>
          </div>
        </div>

        <!-- 合同主体内容 -->
        <div class="print-body">
          <!-- 合同基本信息 -->
          <table class="contract-table">
            <tbody>
              <tr>
                <td class="label">合同名称:</td>
                <td colspan="3">{{ contract.name }}</td>
              </tr>
              <tr>
                <td class="label">客户名称:</td>
                <td>{{ contract.customerName }}</td>
                <td class="label">签约时间:</td>
                <td>{{ formatDate(contract.signTime) }}</td>
              </tr>
              <tr>
                <td class="label">合同期限:</td>
                <td>{{ formatDate(contract.startTime) }} 至 {{ formatDate(contract.endTime) }}</td>
                <td class="label">合同状态:</td>
                <td>{{ getStatusText(contract.status) }}</td>
              </tr>
              <tr>
                <td class="label">合同金额:</td>
                <td>¥{{ formatCurrency(contract.amount) }}</td>
                <td class="label">已收款项:</td>
                <td>¥{{ formatCurrency(contract.receivedAmount) }}</td>
              </tr>
            </tbody>
          </table>

          <!-- 商品明细 -->
          <div class="product-section">
            <h3>商品明细</h3>
            <table class="product-table">
              <thead>
                <tr>
                  <th>序号</th>
                  <th>商品名称</th>
                  <th>单价</th>
                  <th>数量</th>
                  <th>小计</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(product, index) in contract.products" :key="product.pId">
                  <td>{{ index + 1 }}</td>
                  <td>{{ product.pName }}</td>
                  <td>¥{{ formatCurrency(product.price) }}</td>
                  <td>{{ product.count }}</td>
                  <td>¥{{ formatCurrency(product.totalPrice) }}</td>
                </tr>
                <tr v-if="!contract.products || contract.products.length === 0">
                  <td colspan="5" class="no-data">无商品数据</td>
                </tr>
              </tbody>
              <tfoot>
                <tr>
                  <td colspan="4" style="font-weight: bold; text-align: right">总计:</td>
                  <td style="font-weight: bold">¥{{ formatCurrency(contract.amount) }}</td>
                </tr>
              </tfoot>
            </table>
          </div>

          <!-- 备注信息 -->
          <div class="remark-section" v-if="contract.remark">
            <h3>备注</h3>
            <p>{{ contract.remark }}</p>
          </div>

          <!-- 条款说明 -->
          <div class="terms-section">
            <h3>合同条款</h3>
            <ol>
              <li>本合同自双方签字盖章之日起生效。</li>
              <li>双方应严格遵守本合同各项约定，任何一方违约应承担相应违约责任。</li>
              <li>本合同未尽事宜，由双方协商解决，协商不成可向甲方所在地法院提起诉讼。</li>
            </ol>
          </div>

          <!-- 签字区域 -->
          <div class="signature-section">
            <div class="signature-block">
              <p>甲方（销售方）签字:</p>
              <div class="signature-line"></div>
              <p>日期: ________________</p>
            </div>
            <div class="signature-block">
              <p>乙方（购买方）签字:</p>
              <div class="signature-line"></div>
              <p>日期: ________________</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="ContractManage">
import { ref, reactive } from 'vue'
import { ColumnProps } from '@/components/ProTable/interface'
import ProTable from '@/components/ProTable/index.vue'
import { ContractApi } from '@/api/modules/contract/index'
import { CirclePlus, EditPen, Printer, Share } from '@element-plus/icons-vue'
import { ContractStatusList } from '@/configs/enum'
import ContractDialog from './components/ContractDialog.vue'
import ProductDialog from './components/ProductDialog.vue'
import { ElMessage } from 'element-plus'
import { useHandleData } from '@/hooks/useHandleData'

// 确保 productDialogRef 有定义
const productDialogRef = ref()

// 类型定义
interface PageResult<T> {
  list: T[]
  total: number
}
interface ContractProduct {
  pId: number
  pName: string
  price: number
  count: number
  totalPrice: number
}

interface Contract {
  id: number
  number: string
  name: string
  customerName: string
  startTime: string
  endTime: string
  signTime: string
  status: number
  amount: number
  receivedAmount: number
  remark?: string
  products: ContractProduct[]
}
// 合同状态标签类型映射
const contractStatusTagMap: Record<number, { label: string; type: string }> = {
  0: { label: '初始化', type: 'info' },
  1: { label: '审核中', type: 'warning' },
  2: { label: '审核通过', type: 'success' },
  3: { label: '审核未通过', type: 'danger' }
}

// 表格配置项
const columns: ColumnProps[] = [
  { type: 'selection', fixed: 'left', width: 60 },
  {
    prop: 'name',
    label: '合同名称',
    search: { el: 'input' },
    minWidth: 150
  },
  {
    prop: 'number',
    label: '合同编号',
    minWidth: 120,
    search: { el: 'input' }
  },
  {
    prop: 'customerName',
    label: '客户姓名',
    minWidth: 120,
    search: { el: 'input' }
  },
  {
    prop: 'amount',
    label: '合同金额',
    minWidth: 100
  },
  {
    prop: 'receivedAmount',
    label: '已收到款项',
    minWidth: 100
  },
  {
    prop: 'status',
    label: '合同状态',
    enum: Object.values(ContractStatusList),
    search: { el: 'select' },
    tag: true,
    minWidth: 120
  },
  {
    prop: 'signTime',
    label: '签约时间',
    minWidth: 100
  },
  { prop: 'operation', label: '操作', fixed: 'right', width: 200 }
]
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref()

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ isPublic: 0 })
// 处理返回数据格式
// const dataCallback = (data: any) => {
//   return {
//     list: data.list,
//     total: data.total
//   }
// }
const dataCallback = (data: PageResult<any>) => {
  return {
    list: data.list,
    total: data.total
  }
}

// 打开抽屉
const dialogRef = ref()
const openDrawer = (title: string, row: Partial<any> = {}) => {
  let params = {
    title,
    row: { ...row },
    isView: title === '查看',
    api: ContractApi.saveOrEdit,
    getTableList: proTable.value.getTableList,
    maxHeight: '580px'
  }
  dialogRef.value.acceptParams(params)
}
// 打印相关
interface Contract {
  id: number
  number: string
  name: string
  customerName: string
  startTime: string
  endTime: string
  signTime: string
  status: number
  amount: number
  receivedAmount: number
  remark?: string
  //products: ContractProduct[]
  products: Array<{
    pId: number
    pName: string
    price: number
    count: number
    totalPrice: number
  }>
}

// 添加数据验证方法
// const validateContractData = (contract: Contract) => {
//   console.log('验证合同数据:')
//   console.log('- ID:', contract.id)
//   console.log('- 名称:', contract.name)
//   console.log('- 客户:', contract.customerName)
//   console.log('- 金额:', contract.amount)
//   console.log('- 商品数量:', contract.products?.length || 0)

//   if (!contract.products || contract.products.length === 0) {
//     console.warn('合同没有商品数据')
//   } else {
//     contract.products.forEach((product, index) => {
//       console.log(`商品 ${index + 1}:`, product)
//     })
//   }
// }

const printContracts = ref<Contract[]>([])

// 获取状态文本
const getStatusText = (status: number) => {
  const config = contractStatusTagMap[status]
  return config?.label || '未知状态'
}

// 添加格式化函数
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

const formatCurrency = (amount: number | string) => {
  if (!amount) return '0.00'
  return Number(amount).toFixed(2)
}

// 打印单个合同
// 替换现有的打印函数
const printContract = async (row: Contract) => {
  try {
    ElMessage.info('正在生成打印内容...')

    // 获取完整的合同数据
    const response = await ContractApi.getDetail(row.id)
    const contractData = response.data as Contract

    // 数据验证
    if (!contractData) {
      ElMessage.error('获取合同数据失败')
      return
    }

    // 确保商品列表存在
    if (!contractData.products) {
      contractData.products = []
    }

    // 生成打印内容
    const printContent = generatePrintContent([contractData])

    // 使用新窗口打印
    openPrintWindow(printContent, `合同_${contractData.number}`)
  } catch (error) {
    console.error('打印失败:', error)
    ElMessage.error('打印失败，请重试')
  }
}

// 批量打印
const batchPrint = async () => {
  if (!proTable.value) {
    ElMessage.warning('表格未初始化')
    return
  }

  const selectedRows = proTable.value.selectedList
  if (selectedRows.length === 0) {
    ElMessage.warning('请选择要打印的合同')
    return
  }

  try {
    ElMessage.info(`正在准备${selectedRows.length}份合同的打印内容...`)

    // 获取所有选中合同的完整数据
    const contractPromises = selectedRows.map((row) => ContractApi.getDetail(row.id))
    const responses = await Promise.all(contractPromises)
    const contracts = responses.map((response) => response.data)

    // 生成打印内容
    const printContent = generatePrintContent(contracts)

    // 使用新窗口打印
    openPrintWindow(printContent, `批量合同_${new Date().getTime()}`)
  } catch (error) {
    console.error('批量打印失败:', error)
    ElMessage.error('批量打印失败，请重试')
  }
}

// 生成打印内容的HTML
const generatePrintContent = (contracts: Contract[]) => {
  return `
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">
      <title>合同打印</title>
      <style>
        @media print {
          @page {
            margin: 1.5cm;
            size: A4;
          }
          body { 
            font-family: 'SimSun', '宋体', serif;
            font-size: 12px;
            margin: 0;
            padding: 0;
            -webkit-print-color-adjust: exact;
          }
          .print-page {
            page-break-after: always;
            margin: 0;
            padding: 0;
          }
          .print-page:last-child {
            page-break-after: avoid;
          }
        }
        
        body { 
          font-family: 'SimSun', '宋体', serif;
          font-size: 14px;
          line-height: 1.6;
          margin: 0;
          padding: 20px;
        }
        
        .print-page { 
          padding: 20px; 
          margin-bottom: 20px;
        }
        
        .print-header { 
          text-align: center; 
          margin-bottom: 30px;
          border-bottom: 2px solid #000;
          padding-bottom: 20px;
        }
        
        .company-info h1 { 
          margin: 0 0 10px 0; 
          font-size: 24px; 
          font-weight: bold;
        }
        
        .company-info p {
          margin: 0 0 15px 0;
          color: #666;
          font-size: 14px;
        }
        
        .contract-info { 
          display: flex; 
          justify-content: space-between; 
          margin-top: 10px;
          font-size: 14px;
        }
        
        .contract-table { 
          width: 100%; 
          border-collapse: collapse; 
          margin-bottom: 30px;
          border: 1px solid #333;
        }
        
        .contract-table td { 
          padding: 10px; 
          border: 1px solid #333;
          vertical-align: top;
        }
        
        .contract-table .label { 
          background: #f5f5f5; 
          font-weight: bold; 
          width: 120px;
          text-align: center;
        }
        
        .product-section { 
          margin-bottom: 30px;
        }
        
        .product-section h3 {
          text-align: center;
          margin-bottom: 15px;
          border-bottom: 1px solid #333;
          padding-bottom: 10px;
        }
        
        .product-table { 
          width: 100%; 
          border-collapse: collapse; 
          border: 1px solid #333;
        }
        
        .product-table th, .product-table td { 
          border: 1px solid #333; 
          padding: 8px; 
          text-align: center;
        }
        
        .product-table th { 
          background: #f5f5f5; 
          font-weight: bold;
        }
        
        .product-table .no-data {
          height: 100px;
          vertical-align: middle;
          color: #999;
        }
        
        .remark-section { 
          margin-bottom: 30px;
          padding: 15px;
          border: 1px solid #ddd;
          background: #f9f9f9;
        }
        
        .terms-section {
          margin-bottom: 50px;
          font-size: 14px;
        }
        
        .terms-section h3 {
          text-align: center;
          margin-bottom: 15px;
        }
        
        .terms-section ol {
          line-height: 1.8;
          padding-left: 20px;
        }
        
        .signature-section { 
          display: flex; 
          justify-content: space-around; 
          margin-top: 80px;
        }
        
        .signature-block { 
          text-align: center;
          width: 30%;
        }
        
        .signature-line { 
          width: 200px; 
          border-bottom: 1px solid #000; 
          margin: 40px auto 10px;
          height: 1px;
        }
      </style>
    </head>
    <body>
      ${contracts
        .map(
          (contract) => `
        <div class="print-page">
          <div class="print-header">
            <div class="company-info">
              <h1>XX公司销售合同</h1>
              <p>地址：XX市XX区XX路XX号 | 电话：010-XXXXXXXX | 邮箱：contact@example.com</p>
            </div>
            <div class="contract-info">
              <p>合同编号: ${contract.number}</p>
              <p>打印时间: ${new Date().toLocaleString()}</p>
            </div>
          </div>

          <div class="print-body">
            <table class="contract-table">
              <tbody>
                <tr>
                  <td class="label">合同名称:</td>
                  <td colspan="3">${contract.name}</td>
                </tr>
                <tr>
                  <td class="label">客户名称:</td>
                  <td>${contract.customerName}</td>
                  <td class="label">签约时间:</td>
                  <td>${formatDate(contract.signTime)}</td>
                </tr>
                <tr>
                  <td class="label">合同期限:</td>
                  <td>${formatDate(contract.startTime)} 至 ${formatDate(contract.endTime)}</td>
                  <td class="label">合同状态:</td>
                  <td>${getStatusText(contract.status)}</td>
                </tr>
                <tr>
                  <td class="label">合同金额:</td>
                  <td>¥${formatCurrency(contract.amount)}</td>
                  <td class="label">已收款项:</td>
                  <td>¥${formatCurrency(contract.receivedAmount)}</td>
                </tr>
              </tbody>
            </table>

            <div class="product-section">
              <h3>商品明细</h3>
              <table class="product-table">
                <thead>
                  <tr>
                    <th>序号</th>
                    <th>商品名称</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>小计</th>
                  </tr>
                </thead>
                <tbody>
                  ${
                    contract.products && contract.products.length > 0
                      ? contract.products
                          .map(
                            (product, index) => `
                      <tr>
                        <td>${index + 1}</td>
                        <td>${product.pName}</td>
                        <td>¥${formatCurrency(product.price)}</td>
                        <td>${product.count}</td>
                        <td>¥${formatCurrency(product.totalPrice)}</td>
                      </tr>
                    `
                          )
                          .join('')
                      : `<tr><td colspan="5" class="no-data">无商品数据</td></tr>`
                  }
                </tbody>
                <tfoot>
                  <tr>
                    <td colspan="4" style="text-align: right; font-weight: bold">总计:</td>
                    <td style="font-weight: bold">¥${formatCurrency(contract.amount)}</td>
                  </tr>
                </tfoot>
              </table>
            </div>

            ${
              contract.remark
                ? `
              <div class="remark-section">
                <h3>备注</h3>
                <p>${contract.remark}</p>
              </div>
            `
                : ''
            }

            <div class="terms-section">
              <h3>合同条款</h3>
              <ol>
                <li>本合同自双方签字盖章之日起生效。</li>
                <li>双方应严格遵守本合同各项约定，任何一方违约应承担相应违约责任。</li>
                <li>本合同未尽事宜，由双方协商解决，协商不成可向甲方所在地法院提起诉讼。</li>
              </ol>
            </div>

            <div class="signature-section">
              <div class="signature-block">
                <p>甲方（销售方）签字:</p>
                <div class="signature-line"></div>
                <p>日期: ________________</p>
              </div>
              <div class="signature-block">
                <p>乙方（购买方）签字:</p>
                <div class="signature-line"></div>
                <p>日期: ________________</p>
              </div>
            </div>
          </div>
        </div>
      `
        )
        .join('')}
    </body>
    </html>
  `
}

// 打开打印窗口
const openPrintWindow = (content: string, title: string) => {
  const printWindow = window.open('', '_blank')
  if (!printWindow) {
    ElMessage.error('无法打开打印窗口，请允许弹出窗口')
    return
  }

  printWindow.document.write(content)
  printWindow.document.title = title
  printWindow.document.close()

  // 等待内容加载完成后打印
  printWindow.onload = () => {
    printWindow.focus()
    printWindow.print()
  }
}

//开始审核合同
const startApproval = async (row: any) => {
  await useHandleData(ContractApi.startApproval, { id: row.id }, '发起合同审核')
  proTable.value.getTableList()
}
</script>
